<template>
  <div class="bookmark-management">
    <!-- 页面标题和统计信息 -->
    <div class="page-header">
      <h2>网页收藏管理</h2>
      <div class="statistics">
        <el-card class="stat-card">
          <div class="stat-item">
            <span class="stat-value">{{ statistics.total || 0 }}</span>
            <span class="stat-label">总计</span>
          </div>
          <div class="stat-item">
            <span class="stat-value">{{ statistics.video || 0 }}</span>
            <span class="stat-label">视频</span>
          </div>
          <div class="stat-item">
            <span class="stat-value">{{ statistics.blog || 0 }}</span>
            <span class="stat-label">博客</span>
          </div>
          <div class="stat-item">
            <span class="stat-value">{{ statistics.music || 0 }}</span>
            <span class="stat-label">音乐</span>
          </div>
          <div class="stat-item">
            <span class="stat-value">{{ statistics.other || 0 }}</span>
            <span class="stat-label">其他</span>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 搜索和操作栏 -->
    <div class="toolbar">
      <div class="search-section">
        <el-input v-model="searchForm.keyword" placeholder="搜索标题或标签" clearable style="width: 300px"
          @keyup.enter="handleSearch">
          <template #prefix>
            <el-icon>
              <Search />
            </el-icon>
          </template>
        </el-input>

        <el-select v-model="searchForm.type" placeholder="选择类型" clearable style="width: 120px; margin-left: 10px">
          <el-option v-for="(name, value) in BookmarkTypeName" :key="value" :label="name" :value="parseInt(value)" />
        </el-select>

        <el-select v-model="searchForm.sortBy" placeholder="排序字段" style="width: 120px; margin-left: 10px">
          <el-option label="创建时间" value="create_time" />
          <el-option label="更新时间" value="update_time" />
          <el-option label="标题" value="title" />
        </el-select>

        <el-select v-model="searchForm.sortOrder" placeholder="排序方向" style="width: 100px; margin-left: 10px">
          <el-option label="降序" value="desc" />
          <el-option label="升序" value="asc" />
        </el-select>

        <el-button type="primary" @click="handleSearch" style="margin-left: 10px">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </el-button>
      </div>

      <div class="action-section">
        <el-button type="primary" @click="handleAdd">
          <el-icon>
            <Plus />
          </el-icon>
          新增收藏
        </el-button>
        <el-button type="danger" :disabled="selectedIds.length === 0" @click="handleBatchDelete">
          <el-icon>
            <Delete />
          </el-icon>
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />

      <el-table-column prop="id" label="ID" width="100" />

      <el-table-column label="网站信息" width="300">
        <template #default="scope">
          <div class="site-info">
            <img v-if="scope.row.logoUrl" :src="scope.row.logoUrl" alt="logo" class="site-logo"
              @error="handleImageError" />
            <div class="site-details">
              <div class="site-title">
                <a :href="scope.row.url" target="_blank" class="title-link">
                  {{ scope.row.title }}
                </a>
                <el-tag v-if="scope.row.isTop === 1" type="warning" size="small">
                  置顶
                </el-tag>
              </div>
              <div class="site-url">{{ scope.row.url }}</div>
              <div v-if="scope.row.description" class="site-desc">
                {{ scope.row.description }}
              </div>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="type" label="类型" width="80">
        <template #default="scope">
          <el-tag :type="BookmarkTypeTagType[scope.row.type]" size="small">
            {{ BookmarkTypeName[scope.row.type] }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="tags" label="标签" width="120">
        <template #default="scope">
          <span v-if="scope.row.tags">{{ scope.row.tags }}</span>
          <span v-else class="text-muted">-</span>
        </template>
      </el-table-column>

      <el-table-column prop="createTime" label="创建时间" width="160">
        <template #default="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>

      <el-table-column label="操作" min-width="300" fixed="right">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button :type="scope.row.isTop === 1 ? 'warning' : 'info'" size="small"
            @click="handleToggleTop(scope.row)">
            {{ scope.row.isTop === 1 ? '取消置顶' : '置顶' }}
          </el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]" :total="pagination.total" layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" @close="handleDialogClose">
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="100px">
        <el-form-item label="网页标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入网页标题" maxlength="200" />
        </el-form-item>

        <el-form-item label="网页链接" prop="url">
          <el-input v-model="form.url" placeholder="请输入网页链接" maxlength="500" :disabled="isEdit" />
        </el-form-item>

        <el-form-item label="Logo地址" prop="logoUrl">
          <el-input v-model="form.logoUrl" placeholder="请输入Logo地址" maxlength="500" />
        </el-form-item>

        <el-form-item label="网页类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择网页类型" style="width: 100%">
            <el-option v-for="(name, value) in BookmarkTypeName" :key="value" :label="name" :value="parseInt(value)" />
          </el-select>
        </el-form-item>

        <el-form-item label="标签" prop="tags">
          <el-input v-model="form.tags" placeholder="请输入标签" maxlength="200" />
        </el-form-item>

        <el-form-item label="描述信息" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入描述信息" :rows="4" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Delete } from '@element-plus/icons-vue'
import {
  getBookmarkList,
  getBookmarkStatistics,
  createBookmark,
  updateBookmark,
  deleteBookmark,
  batchDeleteBookmarks,
  toggleBookmarkTop,
  BookmarkType,
  BookmarkTypeName,
  BookmarkTypeTagType
} from '@/api/bookmark/bookmark'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const tableData = ref([])
const selectedIds = ref([])
const statistics = ref({})

// 搜索表单
const searchForm = reactive({
  keyword: '',
  type: null,
  sortBy: 'create_time',
  sortOrder: 'desc'
})

// 分页数据
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref()

// 表单数据
const form = reactive({
  id: null,
  title: '',
  url: '',
  logoUrl: '',
  type: null,
  tags: '',
  description: ''
})

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入网页标题', trigger: 'blur' },
    { max: 200, message: '标题长度不能超过200个字符', trigger: 'blur' }
  ],
  url: [
    { required: true, message: '请输入网页链接', trigger: 'blur' },
    { max: 500, message: '链接长度不能超过500个字符', trigger: 'blur' },
    { type: 'url', message: '请输入有效的URL地址', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择网页类型', trigger: 'change' }
  ],
  logoUrl: [
    { max: 500, message: 'Logo地址长度不能超过500个字符', trigger: 'blur' }
  ],
  tags: [
    { max: 200, message: '标签长度不能超过200个字符', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  return isEdit.value ? '编辑收藏' : '新增收藏'
})

// 生命周期
onMounted(() => {
  loadData()
  loadStatistics()
})

// 方法
const loadData = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page,
      size: pagination.size,
      ...searchForm
    }

    // 过滤空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === null || params[key] === undefined) {
        delete params[key]
      }
    })

    const response = await getBookmarkList(params)
    console.log('response = ', response)
    if (response.data.code === 200) {
      tableData.value = response.data.data.list || []
      pagination.total = response.data.data.total || 0
    } else {
      ElMessage.error(response.data.message || '获取数据失败')
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const loadStatistics = async () => {
  try {
    const response = await getBookmarkStatistics()
    if (response.data.code === 200) {
      statistics.value = response.data.data || {}
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

const handleSearch = () => {
  pagination.page = 1
  loadData()
}

const handleAdd = () => {
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(form, {
    id: row.id,
    title: row.title,
    url: row.url,
    logoUrl: row.logoUrl,
    type: row.type,
    tags: row.tags,
    description: row.description
  })
  dialogVisible.value = true
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除收藏"${row.title}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await deleteBookmark(row.id)
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      loadData()
      loadStatistics()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的记录')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedIds.value.length} 条记录吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await batchDeleteBookmarks(selectedIds.value.join(','))
    if (response.data.code === 200) {
      ElMessage.success('批量删除成功')
      selectedIds.value = []
      loadData()
      loadStatistics()
    } else {
      ElMessage.error(response.data.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

const handleToggleTop = async (row) => {
  try {
    const response = await toggleBookmarkTop(row.id)
    if (response.data.code === 200) {
      ElMessage.success(row.isTop === 1 ? '取消置顶成功' : '置顶成功')
      loadData()
    } else {
      ElMessage.error(response.data.message || '操作失败')
    }
  } catch (error) {
    console.error('切换置顶状态失败:', error)
    ElMessage.error('操作失败')
  }
}

const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

const handleCurrentChange = (page) => {
  pagination.page = page
  loadData()
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadData()
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()

    submitLoading.value = true
    let response

    if (isEdit.value) {
      const { id, ...updateData } = form
      response = await updateBookmark(id, updateData)
    } else {
      response = await createBookmark(form)
    }

    if (response.data.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      dialogVisible.value = false
      loadData()
      loadStatistics()
    } else {
      ElMessage.error(response.data.message || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败')
  } finally {
    submitLoading.value = false
  }
}

const handleDialogClose = () => {
  resetForm()
  formRef.value?.clearValidate()
}

const resetForm = () => {
  Object.assign(form, {
    id: null,
    title: '',
    url: '',
    logoUrl: '',
    type: null,
    tags: '',
    description: ''
  })
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'

  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const handleImageError = (event) => {
  event.target.style.display = 'none'
}
</script>

<style scoped>
.bookmark-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 15px 0;
  color: #303133;
}

.statistics {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
}

.stat-card :deep(.el-card__body) {
  display: flex;
  justify-content: space-around;
  padding: 20px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  display: block;
  font-size: 28px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 8px;
}

.search-section {
  display: flex;
  align-items: center;
}

.action-section {
  display: flex;
  gap: 10px;
}

.site-info {
  display: flex;
  align-items: flex-start;
  gap: 10px;
}

.site-logo {
  width: 32px;
  height: 32px;
  border-radius: 4px;
  flex-shrink: 0;
  object-fit: cover;
}

.site-details {
  flex: 1;
  min-width: 0;
}

.site-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 5px;
}

.title-link {
  color: #409eff;
  text-decoration: none;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 200px;
}

.title-link:hover {
  text-decoration: underline;
}

.site-url {
  font-size: 12px;
  color: #909399;
  margin-bottom: 3px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.site-desc {
  font-size: 12px;
  color: #606266;
  line-height: 1.4;
  max-height: 2.8em;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.text-muted {
  color: #c0c4cc;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }

  .search-section {
    flex-wrap: wrap;
    gap: 10px;
  }

  .search-section .el-input,
  .search-section .el-select {
    width: 100% !important;
  }

  .stat-card :deep(.el-card__body) {
    flex-wrap: wrap;
    gap: 15px;
  }

  .stat-item {
    flex: 1;
    min-width: 80px;
  }
}
</style>
